import tkinter as tk
import pymssql
#上级管理部门-删除角色信息的页面
#delete_role_page.py
def open_delete_role_page():
    delete_role_window = tk.Tk()
    delete_role_window.title("上级主管部门-删除角色信息页面")
    delete_role_window.geometry("350x300")

    # 提示文本
    label_name_prompt = tk.Label(delete_role_window, text="请输入要删除的角色姓名：")
    label_name_prompt.pack(pady=5)

    # 输入框
    entry_name = tk.Entry(delete_role_window)
    entry_name.pack(pady=5)

    # 查找按钮
    def find_role_info():
        name_to_delete = entry_name.get()
        # 查找角色信息的逻辑
        role_data = find_role_by_name(name_to_delete)
        display_text.delete(1.0, tk.END)
        display_text.insert(tk.END, role_data)

    find_button = tk.Button(delete_role_window, text="查找角色信息", command=find_role_info)
    find_button.pack(pady=5)

    # 显示框
    display_text = tk.Text(delete_role_window, height=5, width=40)
    display_text.pack()

    # 删除按钮
    def delete_role_info():
        name_to_delete = entry_name.get()
        success = delete_role_by_name(name_to_delete)

        if success:
            result_text = "删除成功！"
        else:
            result_text = "删除失败，请检查输入。"

        label_result.config(text=result_text)

    delete_button = tk.Button(delete_role_window, text="删除角色信息", command=delete_role_info)
    delete_button.pack(pady=5)

    # 提示文本
    label_result = tk.Label(delete_role_window, text="")
    label_result.pack(pady=5)

    delete_role_window.mainloop()

# 从数据库中查找角色信息
def find_role_by_name(name):
    try:
        # 连接到数据库
        conn = pymssql.connect(
            host='localhost',
            user='CSY',
            password='211002624',
            database='植物管理系统',
            as_dict=True
        )
        cursor = conn.cursor()

        # 执行查询语句
        query = f"SELECT * FROM 角色 WHERE 姓名 = '{name}'"
        cursor.execute(query)

        # 获取查询结果
        role_data = cursor.fetchall()

        # 关闭数据库连接
        conn.close()

        # 格式化结果
        formatted_data = ""
        for data in role_data:
            formatted_data += f"账号: {data['账号']}, 姓名: {data['姓名']}, 密码: {data['密码']}, 职位: {data['职位']}\n"

        return formatted_data
    except Exception as e:
        print(f"Error: {e}")
        return "查询失败，请检查数据库连接和查询语句。"

# 从数据库中删除角色信息
def delete_role_by_name(name):
    try:
        # 连接到数据库
        conn = pymssql.connect(
            host='localhost',
            user='CSY',
            password='211002624',
            database='植物管理系统'
        )
        cursor = conn.cursor()

        # 执行删除语句
        query = f"DELETE FROM 角色 WHERE 姓名 = '{name}'"
        cursor.execute(query)

        # 提交更改
        conn.commit()

        # 关闭数据库连接
        conn.close()

        return True
    except Exception as e:
        print(f"Error: {e}")
        return False

